 package com.gmrz.uaf.crypto.internal.keyFormats;
 
 import com.gmrz.uaf.common.UAFRuntimeException;
import com.gmrz.uaf.crypto.CryptoConstants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECPoint;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
 
 public class UAFAlgKeyECCX962Raw extends UAFKeyFmt
 {
   private static final Logger LOG = LogManager.getLogger(UAFAlgKeyECCX962Raw.class);
 
   public UAFAlgKeyECCX962Raw()
   {
     super(CryptoConstants.UAFAlgkey.UAF_ALG_KEY_ECC_X962_RAW);
   }
 
   public PublicKey getKey(byte[] pubKey, int algoSuite)
     throws InvalidKeySpecException, NoSuchAlgorithmException
   {
     LOG.info("getKey UAFAlgKeyECCX962Raw");
     String curveName = getCurveName(algoSuite);
     X9ECParameters x9ECParameters = SECNamedCurves.getByName(curveName);
     if (x9ECParameters != null) {
       ECParameterSpec curveSpec = new ECParameterSpec(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN(), x9ECParameters.getH());
 
       ECPoint point = x9ECParameters.getCurve().decodePoint(pubKey);
       ECPublicKeySpec keySpec = new ECPublicKeySpec(point, curveSpec);
       return KeyFactory.getInstance(this.uafAlgKey.getKeyAlgo(), new BouncyCastleProvider()).generatePublic(keySpec);
     }
 
     throw new UAFRuntimeException("X9ECParameters object is null");
   }
 
   private String getCurveName(int algoSuite)
   {
     CryptoConstants.UAFAlgSign uafAlgSign = CryptoConstants.UAFAlgSign.from(algoSuite);
     if (uafAlgSign == null) {
       String errorMessage = "Invalid authentication algorithm - " + algoSuite;
 
       LOG.error(errorMessage);
       throw new UAFRuntimeException(errorMessage);
     }
     switch (uafAlgSign.getSuite()) {
     case 1:
     case 2:
       return "secp256r1";
     case 3:
     case 4:
       return "secp256k1";
     }
     String errorMessage = "Invalid authentication algorithm - " + algoSuite + " paired with " + toString();
 
     LOG.error(errorMessage);
     throw new UAFRuntimeException(errorMessage);
   }
 }
